package com.atguigu.test.dacahngmainshitidierji.threadpool;

import java.util.concurrent.*;

/**
 * @Author: 19shusheng.com
 * @Description:
 * @Date: Created in 16:30 2020/11/14
 * @Modified By:
 */
public class MyThreadPoolDemo
{
    //手写先乘池
    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(2,
                5,1L,
                TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());

        //new ThreadPoolExecutor.AbortPolicy()  直接抛出异常
        //new ThreadPoolExecutor.CallerRunsPolicy() 被打回的线程是从什么地方来的就从哪个地方执行
        //new ThreadPoolExecutor.DiscardOldestPolicy() 抛弃掉等待时间最长的
        //new ThreadPoolExecutor.DiscardPolicy(直接丢弃新进来的任务
        for (int i = 0; i < 10; i++) {
            executorService.execute(()->{
                System.out.println(Thread.currentThread().getName()+"\t 执行任务");
            });
        }
        executorService.shutdown();
    }

    public  void test(String[] args) {
/*        //获取当前计算机的cpu核数
        System.out.println(Runtime.getRuntime().availableProcessors());*/
         /*第四种使用多线程的方式：线程池
         * 其他三种：继承thread类，实现runnable接口没有返回值不抛异常，实现callable接口有返回值抛异常*/
         //一个池子只有10个线程（一个银行只有10个窗口）
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        //一池一线程
        ExecutorService executorService1 = Executors.newSingleThreadExecutor();
        //一池多线程
        ExecutorService executorService2 = Executors.newCachedThreadPool();




        try {
            for (int i = 0; i < 10; i++) {
                executorService2.execute(()->{
                    System.out.println(Thread.currentThread().getName() + "\t 来执行多个线程的任务了");
                });
                //单个线程的线程池
                executorService1.execute(()->{
                    System.out.println(Thread.currentThread().getName() + "\t 来执行单个线程的任务了");
                });
                //固定线程数的线程池
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"执行固定线程数的任务了");

                });
            }

        }catch (Exception e){}finally {
            executorService2.shutdown();
            executorService1.shutdown();
            executorService.shutdown();
        }
    }
}
